package com.inspur.zhangpeixia.goods.dao;

import com.inspur.zhangpeixia.goods.entity.Category;
import com.inspur.zhangpeixia.goods.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class CategoryDao {

     Connection connection= DBUtils.getConnection();

     public List<Category> listCategory(String keyword){
          try{
               String sql = "select * from t_category where category_name like ?";
               PreparedStatement pst = connection.prepareStatement(sql);
               pst.setString(1,"%"+keyword+"%");
               ResultSet resultSet = pst.executeQuery();
               List<Category> list = new ArrayList<>();
               while (resultSet.next()){
                    Category category = new Category();
                    int categoryId = resultSet.getInt("category_id");
                    category.setCategoryId(categoryId);
                    String categoryName = resultSet.getString("category_name");
                    category.setCategoryName(categoryName);
                    list.add(category);

               }
               return list;
          }catch (Exception e){
               throw new RuntimeException(e);
          }
     }

     public int addCategory(Category category){
          try{
               String sql = "insert into t_category(category_name)values(?)";
               PreparedStatement pst = connection.prepareStatement(sql);
               pst.setString(1,category.getCategoryName());

               return pst.executeUpdate();
          }catch (Exception e){
               throw new RuntimeException(e);
          }
     }

     public int updateCategory(Category category){
          try{
               String sql = "update t_category set category_name=? where category_id=?";
               PreparedStatement pst = connection.prepareStatement(sql);
               pst.setString(1,category.getCategoryName());
               pst.setInt(2,category.getCategoryId());

               return pst.executeUpdate();
          }catch (Exception e){
               throw new RuntimeException(e);
          }
     }

     public int deleteCategory(int id){
          try{
               String sql = "delete from t_category where category_id=?";
               PreparedStatement pst = connection.prepareStatement(sql);

               pst.setInt(1,id);

               return pst.executeUpdate();
          }catch (Exception e){
               throw new RuntimeException(e);
          }
     }


}
